package com.sc.byahi.user.client;

import java.util.Arrays;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.sc.byahi.user.shared.SuccessStory;
import com.sc.byahi.user.shared.SharedUtil;

public class Success extends Composite {

	private static SuccessUiBinder uiBinder = GWT.create(SuccessUiBinder.class);

	interface SuccessUiBinder extends UiBinder<Widget, Success> {
	}

	public Success() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiField
	TextBox myId;
	@UiField
	TextBox spouseId;
	@UiField
	TextArea text;
	@UiField
	Button ok;

	@UiHandler("ok")
	void onButton_1Click(ClickEvent event) {
		final Long myID = SharedUtil.getLong(myId.getText()); 
		final Long spouseID = SharedUtil.getLong(spouseId.getText()); 
		final String details =  text.getText();
		if(myID == null){
			UIUtil.showDialog(Arrays.asList("Please enter groom's profile id."), "profile ID not specified.");
			return;
		}
		if(spouseID == null){
			UIUtil.showDialog(Arrays.asList("Please enter bride's profile id."), "profile ID not specified.");
			return;
		}
		if("".equals(details.trim())){
			UIUtil.showDialog(Arrays.asList("Please enter few words about you marriage."), "Description not specified.");
			return;
		}
		GreetingService.Util.getInstance().verifyProfileIds(Arrays.asList(myID, spouseID), new AsyncCallback<List<Long>>() {
			
			@Override
			public void onSuccess(List<Long> result) {
				if(result.size() != 2){
					UIUtil.showDialog(Arrays.asList("Please check your profile IDs."), "Profile ID not found in database.");
				}else{
					SuccessStory story = new SuccessStory();
					story.setGroomId(myID);
					story.setBrideId(spouseID);
					String detailsTrimmed = details;
					if(details.length() > 400){
						detailsTrimmed = details.substring(0,399);
					}
					story.setText(detailsTrimmed);
					
					GreetingService.Util.getInstance().createSuccessStory(story, new AsyncCallback<Void>() {
						
						@Override
						public void onSuccess(Void result) {
							myId.setText("");
							spouseId.setText("");
							text.setText("");
							UIUtil.showDialog(Arrays.asList("Story submitted successfully."), "Saved.");
						}
						
						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
						}
					});
					
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}
}
